var SpritesheetUpload = new function(){
	
	var spriteImages = [];
	
	var spriteWidth;
	var spriteHeight;
	
	var MAX_WIDTH = 64;
	var MAX_HEIGHT = 64;
	
	var ctx;
	var ctxPrev;
	
	var offsetX = 0;
	
	var activeSprite = 0;
	
	var scrollByPx = true;
	
	var scrollPx = 0;
	
	var prevTimestamp = 0;
	var prevRun = true;
	
	var fps = 10;
	
	var name = "";
	
	var entity = false;
	
	var importImage = function(file, isEntity){
		var filename = file.name;
		var reader = new FileReader();
		reader.onload = function (event) {
			
			var img = new Image();
			img.onload = function () {
			
				if(img.width > MAX_WIDTH || img.height > MAX_HEIGHT){
					if(isEntity){
						alert(H5.t("Error_image_too_large") + " " + MAX_WIDTH + " x " + MAX_HEIGHT + "!");
					} else {
						alert(H5.t("Error_wrong_image_size") + " 16x16!");
					}
				} else {
					if(!spriteWidth) spriteWidth = img.width;
					if(!spriteHeight) spriteHeight = img.height;
					
				
					if(img.width == spriteWidth && img.height == spriteHeight){
						spriteImages.push(this);
						refresh();
					} else {
						alert(H5.t("Error_wrong_image_size") + " " + spriteWidth + " x " + spriteHeight + "!");
					}
				}
			}
			img.src  = event.target.result;
			
			img.name = filename;
			
		};
		
		reader.readAsDataURL(file);
	};
	
	this.init = function(isEntity){
	
		fps = 10;
		name = "";
		spriteImages = [];
		spriteWidth = null;
		spriteHeight = null;
		delete(spriteWidth);
		delete(spriteHeight);
		offsetX = 0;
		activeSprite = 0;
		scrollPx = 0;
	
		if(!isEntity){
			spriteWidth = 16;
			spriteHeight = 16;
			entity = false;
		} else {
			entity = true;
		}
	
		$("#SpritesheetUpload_container").on("drop", function(evt){
			
			for(var i = 0; i < evt.dataTransfer.files.length; i++){
			
				var file = evt.dataTransfer.files[i];
				importImage(file, isEntity);
			
			}
			
			evt.stopPropagation();
			evt.preventDefault();
		});
		
		$("#SpritesheetUpload_container").on("dragover", function(evt){
			$(this).css("border-color","#090");
			$("#SpritesheetUpload_dropText").css("color","#090");
			$("#SpritesheetUpload_container_ovl").show();
			$("#SpritesheetUpload_container_ovl").css("border-color","#090");
			evt.stopPropagation();
			evt.preventDefault();
		});
		$("#SpritesheetUpload_container").on("dragleave", function(evt){
			$(this).css("border-color","#ccc");
			$("#SpritesheetUpload_dropText").css("color","#000");
			$("#SpritesheetUpload_container_ovl").css("border-color","rgba(0,0,0,0)");
		});
		$("#SpritesheetUpload_container").on("dragexit drop", function(evt){
			$(this).css("border-color","#ccc");
			$("#SpritesheetUpload_dropText").css("color","#000");
			$("#SpritesheetUpload_container_ovl").hide();
		});
		
		
		$("#SpritesheetUpload_canvas").attr("width", $("#SpritesheetUpload_container").innerWidth());
		$("#SpritesheetUpload_canvas").attr("height", 70);
		
		$("#SpritesheetUpload_canvas").on("click", function(e){
			positionToImg(e.offsetX);
		});
		
		
		var scrollerMoving = false;
		var scrollerMover;
		var scrollerStartX = 0;
		var scrollerStartLeft = 0;
		
		$("#SpritesheetUpload_canvas_hScrollbar .scroller").on("mousedown",function(e){
			scrollerMover = $(this);
			scrollerMoving = true;
			scrollerStartX = e.pageX;
			scrollerStartLeft = scrollerMover.position().left;
			
			$("body").css("cursor","pointer");
		});
		
		$("*").on("mousemove",function(e){
			if(scrollerMoving){
				var dX = e.pageX - scrollerStartX;
				
				var newLeft = scrollerStartLeft + dX;
				
				var maxWidth = $("#SpritesheetUpload_canvas_hScrollbar").innerWidth() - scrollerMover.innerWidth();
				
				if(newLeft > maxWidth) newLeft = maxWidth;
				if(newLeft < 0) newLeft = 0;
				
				scrollerMover.css("left",newLeft + "px");
				
				if(scrollByPx){
					offsetX = newLeft;
					refresh();
				} else {
					var perc = newLeft / maxWidth;
					offsetX = Math.round(scrollPx * perc);
					refresh();
				}
				
			}
		});
		
		$("*").on("mouseup",function(e){
			scrollerMoving = false;
			$("body").css("cursor","auto");
			$("#SpritesheetUpload_container_ovl").hide();
		});
		
		
		$("#SpritesheetUpload_btnDuplicate").on("click",function(){
			if(!$(this).hasClass("disabled")){
				var newImages = [];
				for(var i = 0; i < activeSprite; i++){
					newImages.push(spriteImages[i]);
				}
				newImages.push(spriteImages[activeSprite]);
				for(var i = activeSprite; i < spriteImages.length; i++){
					newImages.push(spriteImages[i]);
				}
				spriteImages = newImages;
				refresh();
			}
		});
		$("#SpritesheetUpload_btnRemove").on("click",function(){
			if(!$(this).hasClass("disabled")){
				var newImages = [];
				for(var i = 0; i < activeSprite; i++){
					newImages.push(spriteImages[i]);
				}
				for(var i = activeSprite+1; i < spriteImages.length; i++){
					newImages.push(spriteImages[i]);
				}
				spriteImages = newImages;
				if(activeSprite >= spriteImages.length){
					activeSprite = spriteImages.length-1
				}
				refresh();
			}
		});
		$("#SpritesheetUpload_btnMoveBack").on("click",function(){
			if(!$(this).hasClass("disabled")){
				var temp = spriteImages[activeSprite];
				spriteImages[activeSprite] = spriteImages[activeSprite-1];
				spriteImages[activeSprite-1] = temp;
				activeSprite--;
				refresh();
			}
		});
		$("#SpritesheetUpload_btnMoveForward").on("click",function(){
			if(!$(this).hasClass("disabled")){
				var temp = spriteImages[activeSprite];
				spriteImages[activeSprite] = spriteImages[activeSprite+1];
				spriteImages[activeSprite+1] = temp;
				activeSprite++;
				refresh();
			}
		});
		$("#SpritesheetUpload_btnPrevious").on("click",function(){
			if(!$(this).hasClass("disabled")){
				activeSprite--;
				refresh();
			}
		});
		$("#SpritesheetUpload_btnNext").on("click",function(){
			if(!$(this).hasClass("disabled")){
				activeSprite++;
				refresh();
			}
		});
		$("#SpritesheetUpload_btnInvert").on("click",function(){
			if(!$(this).hasClass("disabled")){
				var newImages = [];
				for(var i = 0; i < spriteImages.length; i++){
					newImages.push(spriteImages[spriteImages.length - i - 1]);
				}
				spriteImages = newImages;
				activeSprite = spriteImages.length - activeSprite - 1;
				refresh();
			}
		});
		
		$("#SpritesheetUpload_inFPS").on("change",function(){
			var val = parseInt($(this).val());
			if (val > 0 && val <= 60) {
				fps = val;
			} else {
				alert("Invalid value!"); //TODO translate
				$(this).val(fps);
			}
		});
		
		var canvas = document.getElementById("SpritesheetUpload_canvas");
		ctx = canvas.getContext("2d");
		
		
		var canvasPrev = document.getElementById("SpritesheetUpload_previewCanvas");
		ctxPrev = canvasPrev.getContext("2d");
		
		prevRun = true;
		prevTimestamp = new Date().getTime();
		refreshPrev();
	};
	
	var refresh = function(){
		var width = $("#SpritesheetUpload_canvas").innerWidth();
		var height = 70;
		
		if(width < spriteImages.length * spriteWidth){
			showScroller();
		} else {
			hideScroller();
		}
		
		
		if(spriteImages.length > 0){
			$("#SpritesheetUpload_btnDuplicate").removeClass("disabled");
			$("#SpritesheetUpload_btnRemove").removeClass("disabled");
		} else {
			$("#SpritesheetUpload_btnDuplicate").addClass("disabled");
			$("#SpritesheetUpload_btnRemove").addClass("disabled");
		}
		if(spriteImages.length > 1){
			$("#SpritesheetUpload_btnInvert").removeClass("disabled");
		} else {
			$("#SpritesheetUpload_btnInvert").addClass("disabled");
		}
		if(activeSprite > 0){
			$("#SpritesheetUpload_btnMoveBack").removeClass("disabled");
			$("#SpritesheetUpload_btnPrevious").removeClass("disabled");
		} else {
			$("#SpritesheetUpload_btnMoveBack").addClass("disabled");
			$("#SpritesheetUpload_btnPrevious").addClass("disabled");
		}
		if(activeSprite < spriteImages.length-1){
			$("#SpritesheetUpload_btnMoveForward").removeClass("disabled");
			$("#SpritesheetUpload_btnNext").removeClass("disabled");
		} else {
			$("#SpritesheetUpload_btnMoveForward").addClass("disabled");
			$("#SpritesheetUpload_btnNext").addClass("disabled");
		}
		
		
		
		ctx.fillStyle = '#ffffff';
		ctx.beginPath();
		ctx.rect(0, 0, width, height);
		ctx.fill();
		for(var i = 0; i < spriteImages.length; i++){
			if(spriteImages[i]){
				ctx.drawImage(spriteImages[i], i*spriteWidth-offsetX, (64-spriteHeight)/2);
			}
		}
		if(spriteImages.length > 0){
			ctx.beginPath();
			ctx.rect(activeSprite*spriteWidth-offsetX, (64-spriteHeight)/2, spriteWidth, spriteHeight);
			ctx.lineWidth = 1;
			ctx.strokeStyle = '#ff0000';
			ctx.stroke();
			
			var centerX = activeSprite*spriteWidth-offsetX + spriteWidth/2;
			var centerY = (64-spriteHeight)/2 + spriteHeight + 2;
			ctx.beginPath();
			ctx.moveTo(centerX, centerY);
			ctx.lineTo(centerX+5, centerY+5);
			ctx.lineTo(centerX-5, centerY+5);
			ctx.lineTo(centerX, centerY);
			ctx.fillStyle = '#ff0000';
			ctx.fill();
			
			$("#SpritesheetUpload_filename").html(spriteImages[activeSprite].name);
		} else {
			$("#SpritesheetUpload_filename").html("");
		}
		
		H5.Log.dir(spriteImages);
	};
	
	var showScroller = function(){
		var width = $("#SpritesheetUpload_canvas_hScrollbar").innerWidth();
	
		scrollPx = spriteImages.length * spriteWidth - $("#SpritesheetUpload_canvas").innerWidth();
		var scWidth = 32;
		if(scrollPx < width-32){
			scWidth = width - scrollPx;
			scrollByPx = true;
		} else {
			scrollByPx = false;
		}
		$("#SpritesheetUpload_canvas_hScrollbar .scroller").css("width", scWidth + "px");
		$("#SpritesheetUpload_canvas_hScrollbar .scroller").fadeIn();
	}
	
	var hideScroller = function(){
		$("#SpritesheetUpload_canvas_hScrollbar .scroller").fadeOut();
	}
	
	var positionToImg = function(posX){
		if(!spriteWidth){
			activeSprite = 0;
		} else {
			var pos = posX + offsetX;
			var nr = Math.floor(pos/spriteWidth);
			if(nr < spriteImages.length) activeSprite = nr;
			if(activeSprite >= spriteImages.length) activeSprite = spriteImages.length-1;
		}
		refresh();
	};
	
	var refreshPrev = function(){
		var time = new Date().getTime();
		
		ctxPrev.fillStyle = '#ffffff';
		ctxPrev.beginPath();
		ctxPrev.rect(0, 0, 64, 64);
		ctxPrev.fill();
		
		if(spriteImages.length > 0){
			var activeFrame = Math.round((time - prevTimestamp) * (fps/1000))%spriteImages.length;
			
			
			ctxPrev.drawImage(spriteImages[activeFrame], (64-spriteWidth)/2, (64-spriteHeight)/2);
		}
		
		if(prevRun) setTimeout(refreshPrev, 15);
	};
	
	this.save = function(onSuccess, onError){
	
		if(spriteImages.length < 1){
			
			alert("You need at least one image to save it!");  //TODO translate
			
			onError();
			
		} else {
	
			if(entity && spriteImages.length == 1) spriteImages.push(spriteImages[0]);
	
			var saveCvs = document.createElement('canvas');
			saveCvs.width = spriteImages.length * spriteWidth;
			saveCvs.height = spriteHeight;
		
			var saveCtx = saveCvs.getContext("2d");
			saveCtx.fillStyle = 'rgba(255,255,255,0)';
			saveCtx.beginPath();
			saveCtx.rect(0, 0, saveCvs.width, saveCvs.height);
			saveCtx.fill();
			for(var i = 0; i < spriteImages.length; i++){
				if(spriteImages[i]){
					saveCtx.drawImage(spriteImages[i], i*spriteWidth, 0);
				}
			}
			
			
			
			var sID = WGC.insertSprite({
				image: saveCvs.toDataURL(),
				frames: spriteImages.length,
				width: spriteWidth,
				height: spriteHeight,
				tilesetId: 0,
				fps: fps,
			});
				
			if(entity){
				
				var eID = WGC.insertEntity({
					tilesetId: 0,
					name: $("#SpritesheetUpload_inName").val(),
					isVisible: true,
				});
				
				var esID = WGC.insertEntityState({
					entityId: eID,
					spriteId: sID,
					name: $("#SpritesheetUpload_inName").val(),
					isVisible: true,
				});
				
				WGC.data.entity[eID].defaultStateId = esID;
				
			} else {
				
				WGC.insertBox({
					spriteId: sID,
					tilesetId: 0,
					name: $("#SpritesheetUpload_inName").val(),
				});
			
			}
		
			onSuccess();
	
			prevRun = false;
		
		}
	};
	
	this.close = function(){
	
		prevRun = false;
	};
};